/*
 * DppmBuffer.cpp
 *
 *  Created on: 31/01/2014
 *      Author: Bruno
 */

#include "DppmBuffer.h"
#include "DppmParams.h"
#include "SortedBuffer.h"
#include "Tuple.h"
#include <stdlib.h>
#include <iostream>

using namespace std;


DppmBuffer::DppmBuffer() {
	this->share_param = 0;
	this->sizeT = 0;
}

DppmBuffer::~DppmBuffer() {

	this->bufferShare.clean();
	Tuple * t = NULL;
	while(!this->buffer.empty()){
		this->buffer.pop();
		delete t;
	}

}

void DppmBuffer::init(int** buffRecv, int sizeT, int countT) {

	this->sizeT = sizeT;

	Tuple* tAux;
	for(int i = 0; i < countT; i++){

		tAux = new Tuple(sizeT,buffRecv[i]);

		if(sizeT > this->share_param){
			this->bufferShare.push(tAux);
		}else{
			this->buffer.push(tAux);
		}
	}

}

void DppmBuffer::push(Tuple * t) {


	if((this->sizeT - t->lastAct()) < this->share_param){
		this->buffer.push(t);
	}else{
		this->bufferShare.push(t);
	}

}

Tuple* DppmBuffer::pop() {

	if (this->bufferShare.isEmpty()) {
		Tuple * t = this->buffer.front();
		this->buffer.pop();
		return t;
	}

	return this->bufferShare.pop();

}

int DppmBuffer::getCountT() {

	return this->bufferShare.size();

}

int* clone(int* buff, int size) {

	int * clone = new int[size];
	for (int i = 0; i < size; i++)
		clone[i] = buff[i];

	return clone;
}

bool DppmBuffer::isEmpty() {

	return (this->buffer.empty()) && (this->bufferShare.size() == 0);
}

void DppmBuffer::insert(int** buffRecv, int sizeT, int countT) {

	this->sizeT = sizeT;

	Tuple* t;
	for (int i = 0; i < countT; i++) {

		t = new Tuple(sizeT, buffRecv[i]);
		if (sizeT > this->share_param) {
			this->bufferShare.push(t);
		} else {
			this->buffer.push(t);
		}
	}
}

int DppmBuffer::getKTuples(int count, int** &buff) {

	Tuple * t = NULL;
	int * buffTuple = NULL;
	for (int i = 0; (i < count) && (this->bufferShare.size() > 0); i++) {
		t = this->bufferShare.pop();
		buffTuple = t->getArray();
		for(int j = 0; j < t->getLength(); j++){
			buff[i][j] = buffTuple[j];
		}
	}
	return 0;
}

void DppmBuffer::setShareParam(int sp){
	this->share_param = sp;
}

int DppmBuffer::getShareParam(){
	return this->share_param;
}

void DppmBuffer::print(){


}
